﻿using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Security;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Threading.Tasks;
using WinHBM.Config;
using WinHBM.Core.Net.Http;

namespace WinHBM.Utils
{
    public class UtilRequest
    {
        private static readonly log4net.ILog Logger = log4net.LogManager.GetLogger(typeof(UtilRequest));
        private static AppConfig config = AppConfig.Instance;

        public static JObject DoRequest(string url, RequestMethod method, JObject body)
        {
            
            string result;
            string RequestPrefix = config["apiHost"];
            try
            {

                if (!url.StartsWith("http") && !url.StartsWith("https"))
                {
                    url = RequestPrefix + url;
                }

                if (url.StartsWith("https", StringComparison.OrdinalIgnoreCase))
                {
                    ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
                }

                HttpWebRequest webReq = HttpWebRequest.Create(url) as HttpWebRequest;
                webReq.Method = method.ToString();
                webReq.ContentType = "application/json";
                if (!String.IsNullOrEmpty(TokenHolder.Token))
                {
                    webReq.Headers["Authorization"] = "Bearer " + TokenHolder.Token;
                }

                if (method.Equals(RequestMethod.POST) && body != null)
                {
                    byte[] btBodys = Encoding.UTF8.GetBytes(body.ToString());
                    webReq.ContentLength = btBodys.Length;
                    Stream bodyStream = webReq.GetRequestStream();
                    bodyStream.Write(btBodys, 0, btBodys.Length);
                    bodyStream.Close();
                }


                HttpWebResponse webResponse = (HttpWebResponse)webReq.GetResponse();
                StreamReader steamReader = new StreamReader(webResponse.GetResponseStream(), Encoding.UTF8);
                result = steamReader.ReadToEnd();

                steamReader.Close();
                //webReq.Abort();
                webResponse.Close();
            }
            catch (Exception e)
            {
                Dictionary<String, Object> ExceptionDic = new Dictionary<String, Object>();
                ExceptionDic.Add("errcode", -1);
                ExceptionDic.Add("message", e.Message);
                result = JsonConvert.SerializeObject(ExceptionDic);
                Logger.Error(e);
            }

            return JObject.Parse(result);
        }

        private static bool CheckValidationResult(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors)
        {
            return true; //总是接受  
        }
    }
}
